package com.yanq.liancar.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxPhotoTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogChooseImage;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.GvServiceAdapter;
import com.yanq.liancar.adapter.GvServiceImgAdapter2;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.FullServiceBean;
import com.yanq.liancar.bean.ServiceTypeBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class SmallBModifyServiceActivity extends BaseToolbarActivity {

    @BindView(R.id.gridview_service)
    GridView gridviewService;
    @BindView(R.id.et_servicename)
    EditText etServicename;
    @BindView(R.id.et_serviceprice)
    EditText etServiceprice;
    @BindView(R.id.et_serviceblurb)
    EditText etServiceblurb;
    @BindView(R.id.et_servicematter)
    EditText etServicematter;
    @BindView(R.id.img_gridview)
    GridView imgGridview;
    @BindView(R.id.tv_modify)
    TextView tvModify;
    private GvServiceAdapter gvServiceAdapter;
    private GvServiceImgAdapter2 gvServiceImgAdapter;
    private List<ServiceTypeBean> typeList = new ArrayList<>();
    private List<FullServiceBean.DataBean.FilesBean> imglist = new ArrayList<>();
    private int intType;
    private Uri resultUri;
    private File file, fileName;
    private List<File> fileList = new ArrayList<>();
    private LinkedList<String> imgIdList = new LinkedList<>();
    private FullServiceBean.DataBean dataBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_small_b_servicemodify);
        ButterKnife.bind(this);
        Utils.setStatusBar(this, true, false);
        mTvTitle.setText("修改服务");


        dataBean = (FullServiceBean.DataBean) getIntent().getSerializableExtra("BSreviceAdmBean");
        etServicename.setText(dataBean.getServiceName());
        etServiceprice.setText("¥" + dataBean.getServicePrice());
        etServiceblurb.setText(dataBean.getServiceInfo());
        etServicematter.setText(dataBean.getServiceRemark());
        addServiceType(dataBean.getServiceType());
        imglist = dataBean.getFiles();
        intType=dataBean.getServiceType();

        addImg();
    }

    private void addServiceType(int type) {
        ServiceTypeBean bean1 = new ServiceTypeBean();
        bean1.setName("精致洗车");
        bean1.setServiceType(1);
        if (type == 1) {
            bean1.setChecked(true);
        } else {
            bean1.setChecked(false);
        }
        typeList.add(bean1);

        ServiceTypeBean bean2 = new ServiceTypeBean();
        bean2.setName("标准洗车");
        if (type == 2) {
            bean2.setChecked(true);
        } else {
            bean2.setChecked(false);
        }
        bean2.setServiceType(2);
        typeList.add(bean2);

        ServiceTypeBean bean3 = new ServiceTypeBean();
        bean3.setName("美容养护");
        if (type == 3) {
            bean3.setChecked(true);
        } else {
            bean3.setChecked(false);
        }
        bean3.setServiceType(3);
        typeList.add(bean3);

        ServiceTypeBean bean4 = new ServiceTypeBean();
        bean4.setName("到店保养");
        if (type == 4) {
            bean4.setChecked(true);
        } else {
            bean4.setChecked(false);
        }
        bean4.setServiceType(4);
        typeList.add(bean4);

        ServiceTypeBean bean5 = new ServiceTypeBean();
        bean5.setName("钣金喷漆");
        if (type == 5) {
            bean5.setChecked(true);
        } else {
            bean5.setChecked(false);
        }
        bean5.setServiceType(5);
        typeList.add(bean5);

        ServiceTypeBean bean6 = new ServiceTypeBean();
        bean6.setName("代办服务");
        if (type == 6) {
            bean6.setChecked(true);
        } else {
            bean6.setChecked(false);
        }
        bean6.setServiceType(6);
        typeList.add(bean6);

        gvServiceAdapter = new GvServiceAdapter(mContext, typeList);
        gridviewService.setAdapter(gvServiceAdapter);
//        gridviewService.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                for (int i = 0; i < typeList.size(); i++) {
//                    if (i == position) {
//                        typeList.get(i).setChecked(true);
//                        intType = typeList.get(position).getServiceType();
//                    } else {
//                        typeList.get(i).setChecked(false);
//                    }
//                }
//                gvServiceAdapter.setData(typeList);
//            }
//        });
    }

    private void addImg() {
        gvServiceImgAdapter = new GvServiceImgAdapter2(mContext, imglist);
        imgGridview.setAdapter(gvServiceImgAdapter);
        imgGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (imglist.size() < 4) {
                    if (position == parent.getChildCount() - 1) {
                        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(SmallBModifyServiceActivity.this);
                        dialogChooseImage.show();
                    }
                }
            }
        });
        gvServiceImgAdapter.setDeleteClickListner(new GvServiceImgAdapter2.onDeleteClickListner() {
            @Override
            public void onDeleteListner(View view, int position) {

                if ("".equals(imglist.get(position).getId()) || imglist.get(position).getId() != 0) {
                    imgIdList.add(imglist.get(position).getId() + "");
                } else {
                    Uri uri = Uri.parse(imglist.get(position).getWebPath());
                    fileName = new File(RxPhotoTool.getImageAbsolutePath(mContext, uri));
                    for (int i = 0; i < fileList.size(); i++) {
                        if (fileList.get(i).getName().equals(fileName.getName())) {
                            fileList.remove(i);
                        }
                    }
                }
                imglist.remove(position);
                gvServiceImgAdapter.notifyDataSetChanged();
            }
        });
    }

    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);

        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));

        Log.e("initUCrop: ", destinationUri + "");

        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.main_color));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.main_color));

        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
//        options.setOvalDimmedLayer(true);
        //设置是否展示矩形裁剪框
        // options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);

        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        initMySelfImg(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initMySelfImg(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(data.getData());
                }

                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(RxPhotoTool.imageUriFromCamera);

                }

                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                resultUri = RxPhotoTool.cropImageUri;

                FullServiceBean.DataBean.FilesBean filesBean = new FullServiceBean.DataBean.FilesBean();
                filesBean.setWebPath(resultUri + "");
                imglist.add(filesBean);

                file = new File(RxPhotoTool.getImageAbsolutePath(this, resultUri));
                fileList.add(file);
                gvServiceImgAdapter.notifyDataSetChanged();
                //gvServiceImgAdapter.setData(fileList);
                //initUploadImage(file1);
                //RxToast.success("剪辑成功");
                break;

            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    FullServiceBean.DataBean.FilesBean filesBean1 = new FullServiceBean.DataBean.FilesBean();
                    filesBean1.setWebPath(resultUri + "");
                    imglist.add(filesBean1);

                    file = new File(RxPhotoTool.getImageAbsolutePath(this, resultUri));
                    fileList.add(file);
                    LogUtils.e("fileList.size===", fileList.size() + "");
                    gvServiceImgAdapter.notifyDataSetChanged();
                    //gvServiceImgAdapter.setData(fileList);
                    //initUploadImage(file2);
                    //RxToast.success("剪辑成功");
                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                RxToast.error(cropError.getMessage());
                Log.e("asd", "initMySelfImg: " + cropError.getMessage());
                break;
            default:
                break;
        }
    }

    //修改车辆服务
    private void initOkGoAddService() {
        String price=etServiceprice.getText().toString().trim().substring(1);
        OkGo.<String>post(Config.s + "llc/updateCarService")
                .tag(this)
                .params("token", UserBean.getbToken(mContext))
                .params("id", dataBean.getId())
                .params("serviceType", intType)
                .params("serviceName", etServicename.getText().toString().trim())
                .params("serviceyuanprice", price)
                .params("serviceInfo", etServiceblurb.getText().toString().trim())
                .params("serviceRemark", etServicematter.getText().toString().trim())
                .addFileParams("file", fileList)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {
                            RxToast.success(baseBean.getOutputMessage());
                            initOkGoDelImg();
                            finish();
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });

    }

    //删除服务图片
    private void initOkGoDelImg() {
        OkGo.<String>post(Config.s + "llc/fileController/deleteFilesByIds")
                .tag(this)
                .params("token", UserBean.getbToken(mContext))
                .addUrlParams("ids", imgIdList)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {

                        } else {
                            //RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });

    }

    @OnClick(R.id.tv_modify)
    public void onViewClicked() {
        initOkGoAddService();
    }
}
